package com.example.demo.lock;

import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component("redissionLock")
public class RedissionLock implements RedisLock {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public boolean lock(String lockValue, int seconds) {
        /*final RLock fairLock = redissonClient.getFairLock(lockValue);
        boolean result = false;
        try {
            result = fairLock.tryLock(seconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return false;
    }

    @Override
    public boolean tryLock(String lockValue, int seconds) {
        final RLock fairLock = redissonClient.getFairLock(lockValue); //这里的seconds是等待的时间，而不是锁自动失效时间
        boolean result = false;
        try {
            result = fairLock.tryLock(seconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean release(String lock) {
        final RLock fairLock = redissonClient.getFairLock(lock);
        fairLock.unlock();
        return true;
    }
}
